package com.lib.common.utils;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

//import io.realm.Realm;
//import io.realm.RealmConfiguration;

public class SCDatabase {
    private SCSQLiteDatabase mDatabase;
    final static private SCDatabase signal = new SCDatabase();

    static public SCDatabase shareObject(){return signal;}
    public void init(Context context){
//        Realm.init(context);
//
//        RealmConfiguration configuration = new RealmConfiguration.Builder()
//                .name("lion")
//                //.encryptionKey("111111".getBytes())
////                .schemaVersion(1)
//                .build();
//        Realm.setDefaultConfiguration(configuration);
        mDatabase = new SCSQLiteDatabase(context);
    }

    public void deinit(){
        mDatabase.close();
    }

    public void updateCacheInfo(String key, String cache){
        boolean bExist = checkCacheExist(key);

        SQLiteDatabase lDatabase = mDatabase.getWritableDatabase();
        if(lDatabase != null){
            if(bExist){
                String sql = String.format("update %s set cache='%s', date='%s' where key='%s'", SYSTEM_CACHE_TABLE,
                        cache, date(), key);
                lDatabase.beginTransaction();
                lDatabase.execSQL(sql);
                lDatabase.setTransactionSuccessful();
                lDatabase.endTransaction();
            }else{
                insertCacheExist(key, cache);
            }

            lDatabase.close();
        }
    }
//    static public Realm getRealmInstance(){
//        Realm realm = Realm.getDefaultInstance();
//        return realm;
//    }

    public String queryCache(String key){
        SQLiteDatabase lDatabase = mDatabase.getWritableDatabase();
        if(lDatabase != null){
            Cursor lCursor = null;
            try {
                lCursor = lDatabase.rawQuery(String.format("select * from %s where key='%s';", SYSTEM_CACHE_TABLE, key), null);
                String cache = null;
                while (lCursor.moveToNext()){
                    int index = lCursor.getColumnIndex("cache");
                    cache = lCursor.getString(index);
                }

                return cache;
            }catch (SQLException e){
                e.printStackTrace();
            }finally {
                if(lCursor != null){
                    lCursor.close();
                }
                lDatabase.close();
            }
        }
        return null;
    }
    private void insertCacheExist(String key, String cache){
        SQLiteDatabase lDatabase = mDatabase.getWritableDatabase();
        if(lDatabase != null){
            String sql = String.format("insert into %s (key, cache, date) values('%s', '%s', '%s');", SYSTEM_CACHE_TABLE, key, cache, date());
            lDatabase.execSQL(sql);
            lDatabase.close();
        }

    }
    private boolean checkCacheExist(String key){
        SQLiteDatabase lDatabase = mDatabase.getReadableDatabase();
        if(lDatabase != null){
            Cursor lCursor = lDatabase.rawQuery(String.format("select * from %s where key='%s';", SYSTEM_CACHE_TABLE, key), null);
            boolean ret =  lCursor.getCount() > 0;
            lCursor.close();
            lDatabase.close();
            return ret;
        }
        return false;
    }

//    public void saveDownload(CSDownloadManagerUtil.DownloadTask pDownloadTask){
//        if(checkDownloadTaskExist(pDownloadTask.getUrl())){
//            return;
//        }
//
//        SQLiteDatabase lDatabase = mDatabase.getWritableDatabase();
//        if(lDatabase != null){
//            String sql = String.format("insert into %s(url, local, status, key, date) values('%s', '%s', '%d', '%s', '%s');",
//                    DOWNLOAD_TABLE, pDownloadTask.getUrl(), pDownloadTask.getLocal(), pDownloadTask.getStatus(), pDownloadTask.getKey(),
//                    date());
//
//            lDatabase.execSQL(sql);
//            lDatabase.close();
//        }
//    }
//
//    public void updateDownloadStatus(String url, int status){
//        if(!checkDownloadTaskExist(url)){
//            return;
//        }
//
//        SQLiteDatabase lDatabase = mDatabase.getWritableDatabase();
//        if(lDatabase != null){
//            String sql = String.format("update %s set status='%d' where url='%s';", DOWNLOAD_TABLE, status, url);
//            lDatabase.execSQL(sql);
//            lDatabase.close();
//        }
//    }
//    public ArrayList<CSDownloadManagerUtil.DownloadTask> queryDownload(int status){
//        ArrayList<CSDownloadManagerUtil.DownloadTask> lTasks = new ArrayList<>();
//        SQLiteDatabase lDatabase = mDatabase.getWritableDatabase();
//        if(lDatabase != null){
//            String sql = String.format("select * from %s where status='%d';", DOWNLOAD_TABLE, status);
//
//            Cursor lCursor = lDatabase.rawQuery(sql, null);
//            while (lCursor.moveToNext()){
//                String url = lCursor.getString(lCursor.getColumnIndex("url"));
//                String local = lCursor.getString(lCursor.getColumnIndex("local"));
//                int lStatus = lCursor.getInt(lCursor.getColumnIndex("status"));
//                String key = lCursor.getString(lCursor.getColumnIndex("key"));
//                String date = lCursor.getString(lCursor.getColumnIndex("date"));
//
//                CSDownloadManagerUtil.DownloadTask lTask = new CSDownloadManagerUtil.DownloadTask(key, url);
//                lTask.setLocal(local);
//                lTask.setStatus(lStatus);
//                lTask.setDate(date);
//
//                lTasks.add(lTask);
//            }
//
//            lCursor.close();;
//            lDatabase.close();
//        }
//        return lTasks;
//    }
//
//    public void removeDownload(String url){
//        SQLiteDatabase lDatabase = mDatabase.getWritableDatabase();
//        if(lDatabase != null){
//            String sql = String.format("delete from %s where url='%s';", url);
//            lDatabase.execSQL(sql);
//            lDatabase.close();
//        }
//    }
//    private boolean checkDownloadTaskExist(String url){
//        SQLiteDatabase lDatabase = mDatabase.getWritableDatabase();
//        if(lDatabase != null){
//            String sql = String.format("select * from %s where url='%s';", DOWNLOAD_TABLE, url);
//            Cursor lCursor = lDatabase.rawQuery(sql, null);
//            boolean lExist = lCursor.getCount() > 0;
//            lCursor.close();
//            lDatabase.close();;
//
//            return lExist;
//        }
//        return false;
//    }

    private String date(){
        SimpleDateFormat lDateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        lDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date lDate = new Date(System.currentTimeMillis());
        String dateStr = lDateFormat.format(lDate);
        return dateStr;
    }

    public class SCSQLiteDatabase extends SQLiteOpenHelper{

        public SCSQLiteDatabase(Context pContext){
            super(pContext, "livon.db", null, 1);
            getWritableDatabase().beginTransaction();
            getWritableDatabase().endTransaction();
        }

        @Override
        public void onConfigure(SQLiteDatabase db) {
            super.onConfigure(db);
        }

        @Override
        public void onCreate(SQLiteDatabase pSQLiteDatabase) {
            try {
                pSQLiteDatabase.execSQL(CREATE_SYSTEM_CACHE_TABLE);
                pSQLiteDatabase.execSQL(CREATE_DOWNLOAD_TABLE);
            }catch (SQLException pE){
                pE.printStackTrace();
                Log.d(TAG, "onCreate: FAILED ");
            }
            Log.d(TAG, "onCreate: SUCCESS ");
        }

        @Override
        public void onUpgrade(SQLiteDatabase pSQLiteDatabase, int pI, int pI1) {
            Log.d(TAG, "onUpgrade: ");
        }

    }

    static private String SYSTEM_CACHE_TABLE = "SC_SYSTEM_CACHE";

    static private String CREATE_SYSTEM_CACHE_TABLE = "CREATE TABLE if not exists `SC_SYSTEM_CACHE` (\n" +
            "  `key` VARCHAR(64) NOT NULL,\n" +
            "  `cache` VARCHAR(1024),\n" +
            "  `date` VARCHAR(32),\n" +
            "  PRIMARY KEY (`key`));";
    static private String DOWNLOAD_TABLE = "CREATE_DOWNLOAD_TABLE";
    static private String CREATE_DOWNLOAD_TABLE = "CREATE TABLE `CREATE_DOWNLOAD_TABLE` (\n" +
            "  `url` VARCHAR(1024) NOT NULL,\n" +
            "  `status` INT,\n" +
            "  `local` VARCHAR(1024),\n" +
            "  `key` VARCHAR(64) ,\n" +
            "  `date` VARCHAR(64) ,\n" +
            "  PRIMARY KEY (`url`));";

    static private String TAG = "SCDatabase";

}
